package com.mango.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/8/13 22:50
 * 统一处理异常的aop配置类
 * @Aspect 声明他是一个aop的类
 */
@Component
@Aspect
public class ServiceLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

        /**
         *  @Pointcut("execution(* com.mango.community.service.*.*(..))")
         *  申明日志的切入点
         *  execution 关键字
         *  *           com.mango.community.service. *.    *          (..)  )
         *  所有的返回值  包名                         所有类 所有方法   所有的参数
         */
        @Pointcut("execution(* com.mango.community.service.*.*(..))")
        public void pointcut(){}

    /**
     *@Before("pointcut()")  前置通知，在切入点之前
     * @param joinPoint
     */
    @Before("pointcut()")
    public void before(JoinPoint joinPoint){
        //日志的格式 [用户的ip]在[时间]访问了[com.mango.community.service.xxx]方法
        //获取request对象来获取用户的ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(requestAttributes == null){
                return;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteHost();
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //获取调用那个类的那个方法
       String target= joinPoint.getSignature().getDeclaringTypeName() + "." +joinPoint.getSignature().getName();
       //输出日志   %s 占位符
       logger.info(String.format("用户[%s],在[%s]访问了[%s].",ip,now,target));
    }
}
